//
//  HWViewSellNoController.m
//  HWanGame
//
//  Created by 陈道斌 on 2019/9/28.
//  Copyright © 2019 Chendaobin. All rights reserved.
//

#import "HWViewSellNoController.h"
#import "HWMainHaoView.h"
#import "HWMaiHaoCell.h"
#import "HWSellNOModel.h"
#define MAX_LIMIT_NUMS 90
#import "LFOpinionView.h"
#import <CTAssetsPickerController.h>
#import "CasesIconItem.h"
#import "ChooseCollectionViewCell.h"

// 项目中黑色字体的颜色
#define    wholeProjectBlackFontColor  RGB(51,51,51)

@interface HWViewSellNoController ()<HWMainHaoViewDelegate,UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,CTAssetsPickerControllerDelegate,ChooseCollectionViewCellDelegate,UITextFieldDelegate,UINavigationControllerDelegate>{
    
    NSInteger  max;
    
}


@property(strong,nonatomic)HWMainHaoView *maiHaoView;
@property(strong,nonatomic)UIView *lowerPartView;
@property(strong,nonatomic) UITableView *mainaTableVie;
@property(strong,nonatomic) NSArray *tyapeArray;
@property(strong,nonatomic) NSArray *miashuArray;
@property(strong,nonatomic) NSMutableArray *neiRongMuArr;
@property(strong,nonatomic) NSMutableArray *dataMuArr;
@property(strong,nonatomic) UIView *footView;
@property(strong,nonatomic) UITextField *nameTexField;
@property(strong,nonatomic) UIView *inputView;
@property (nonatomic, strong) LFOpinionView *textView;
@property(nonatomic,strong) UIView *screenshotsView;

@property(strong,nonatomic) UITextField *erjiTextField1;
@property(strong,nonatomic) UICollectionView *collectionView;
@property(strong,nonatomic) NSMutableArray *dataMuArry;


@property(strong,nonatomic) UITextField *biaotinamete1feild;

@property(strong,nonatomic) NSMutableArray *cunchuUrlStrMutabelArr;


@end

@implementation HWViewSellNoController

-(UITableView *)mainaTableVie {
    
    if (_mainaTableVie == nil
        ) {
        
        _mainaTableVie = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH-44-TabbarSafeBottomMargin) style:UITableViewStylePlain];
        _mainaTableVie.delegate = self;
        _mainaTableVie.dataSource = self;
        _mainaTableVie.separatorStyle = UITableViewCellSeparatorStyleNone;
        _mainaTableVie.backgroundColor = [UIColor whiteColor];
        
        
        
        
    }
    return   _mainaTableVie ;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setCommonProperties];
    [self setupTheData];
    
    
    // 设置一些常用的属性
    [self setupUI];
    
    [self addBouncedView];
    
    [self addLowerPartView];
    
}

#pragma  mark  --------- 设置数据
- (void)setupTheData {
    max = 6;
    self.dataMuArry =  [[NSMutableArray alloc]init];
   // NSDictionary *dic = @{@"iconImage":@"", @"isdelete":@"0"};
 //   CasesIconItem  *p1 = [CasesIconItem mj_objectWithKeyValues:dic];
    CasesIconItem  *p1 = [[CasesIconItem alloc]init];
    p1.iconImage = [UIImage imageNamed:@""];
    [self.dataMuArry addObject:p1];
    
    

}




- (void)setCommonProperties {
    
     self.tyapeArray = @[@"游戏名称",@"操作系统",@"添加小号",@"游戏区服",@"售价",@"出售可得"];
    self.miashuArray = @[@"请选择游戏",@"请选择操作系统",@"请选择小号",@"请选择游戏区服",@"请输入出售金额",@"出售可得"];
    
    self.neiRongMuArr = [[NSMutableArray alloc]init];
    for (int i = 0 ; i < self.miashuArray.count; i++) {
        [self.neiRongMuArr addObject:@""];
    }
    NSArray *arr = @[@{@"mingchenStr":@"游戏名称",@"mishuString":@"请选择游戏",@"isdianji":@"0",@"neirongStr":@""},@{@"mingchenStr":@"操作系统",@"mishuString":@"请选择操作系统",@"isdianji":@"0",@"neirongStr":@""},@{@"mingchenStr":@"小号名称",@"mishuString":@"请选择小号",@"isdianji":@"0",@"neirongStr":@""},@{@"mingchenStr":@"游戏区服",@"mishuString":@"请选择游戏区服",@"isdianji":@"1",@"neirongStr":@""},@{@"mingchenStr":@"售价",@"mishuString":@"请输入出售金额",@"isdianji":@"1",@"neirongStr":@""},
        @{@"mingchenStr":@"出售可得",@"mishuString":@"",@"isdianji":@"0",@"neirongStr":@""}];
  
     self.dataMuArr  = [HWSellNOModel mj_objectArrayWithKeyValuesArray:arr];
    
    
    
     HWYouXixiaoHaoModel *modle =  self.chuanmodel.data[0];
     
     
     HWSellNOModel *model0 =  self.dataMuArr[0];
     model0.neirongStr = modle.gname;
     
      HWSellNOModel *model2 =  self.dataMuArr[2];
     model2.neirongStr = modle.role_name;
    // [self.mainaTableVie reloadData];
    
    
}

- (void)setChuanmodel:(HWXiaoGroupModel *)chuanmodel  {
    
    _chuanmodel = chuanmodel;
    
//    HWYouXixiaoHaoModel *modle =  chuanmodel.data[0];
//
//
//    HWSellNOModel *model0 =  self.dataMuArr[0];
//    model0.neirongStr = modle.gname;
//
//     HWSellNOModel *model2 =  self.dataMuArr[2];
//    model2.neirongStr = modle.role_name;
//    [self.mainaTableVie reloadData];
    
}


- (void)setupUI {
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"我要卖号";
    [self.view addSubview:self.mainaTableVie];
    
    self.footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 6+40+150+6+40+160+30)];
    self.footView.backgroundColor = [UIColor whiteColor];
    self.mainaTableVie.tableFooterView = self.footView;
    
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 6)];
    view1.backgroundColor = RGB(245, 245, 245);
    [self.footView addSubview:view1];
    
    
    
    
    UILabel   *miaoShuLabel  = [[UILabel alloc]initWithFrame:CGRectMake(16, 6, 100, 40)];
    miaoShuLabel.text = @"标题";
    miaoShuLabel.font = [UIFont systemFontOfSize:13];
    miaoShuLabel.textColor = RGB(50, 50, 50);
    [self.footView addSubview: miaoShuLabel];
    
    UIView *fengexianView = [[UIView alloc]initWithFrame:CGRectMake(0, 45, kScreenW, 1)];
    fengexianView.backgroundColor = RGB(232, 232, 242);
    [self.footView addSubview:fengexianView];
    
    
    UITextField   *biaotinameTextField = [[UITextField alloc]initWithFrame:CGRectMake(kScreenW-200-27, 6, 200, 40)];
    biaotinameTextField.placeholder = @"请设置标题";
    biaotinameTextField.font = [UIFont systemFontOfSize:12];
    biaotinameTextField.textAlignment = NSTextAlignmentRight;
    self.biaotinamete1feild = biaotinameTextField;
    
    [self.footView  addSubview:biaotinameTextField];
    
    self.inputView = [[UIView alloc]initWithFrame:CGRectMake(0, miaoShuLabel.bottom, kScreenW, 150+40)];
    self.inputView.backgroundColor = [UIColor whiteColor];
    [self.footView addSubview:self.inputView];
    
    
    
    UIView *basieview = [[UIView alloc]initWithFrame:CGRectMake(15, 15, kScreenW-15*2, 120)];
    basieview.backgroundColor = [UIColor whiteColor];
    basieview.userInteractionEnabled = YES;
    basieview.layer.borderWidth = 1;
    basieview.layer.borderColor = RGB(232, 232, 242).CGColor;
    basieview.layer.cornerRadius = 3;
    basieview.layer.masksToBounds = YES;
    [self.inputView addSubview:basieview];
    
    
    _textView = [[LFOpinionView alloc] init];
    _textView.alwaysBounceVertical = YES;
    _textView.userInteractionEnabled = YES;
    _textView.delegate = self;
    //     _textView.x = 10;
    //     _textView.y = 0;
    _textView.frame = CGRectMake(10, 0, kScreenW- 20-30, 120);
  //  _textView.backgroundColor = [UIColor redColor];
    _textView.textColor = RGB(51, 51, 51);
    _textView.placeholder = @"请填写小号描述（最低不少于15字符,最多不超过90个字符）";
    _textView.font = [UIFont systemFontOfSize:14];
    [basieview addSubview:_textView];
    
    

    
     UILabel   *miallabel  = [[UILabel alloc]initWithFrame:CGRectMake(16, 150, 100, 40)];
     miallabel.text = @"二级密码";
     miallabel.font = [UIFont systemFontOfSize:13];
     miallabel.textColor = RGB(51, 51, 51);
     [self.inputView addSubview: miallabel];
    
    
        UITextField   *erjiTextField = [[UITextField alloc]initWithFrame:CGRectMake(100, 150, kScreenW-20-100, 40)];
        erjiTextField.placeholder = @"请输入二级密码";
        erjiTextField.font = [UIFont systemFontOfSize:12];
         erjiTextField.delegate = self;
        self.erjiTextField1 = erjiTextField;
      // erjiTextField.backgroundColor = [UIColor redColor];
        erjiTextField.textAlignment = NSTextAlignmentRight;
        [self.inputView  addSubview:erjiTextField];
    
    
    
    
    
     
    
    self.screenshotsView = [[UIView alloc]initWithFrame:CGRectMake(0, self.inputView.bottom, kScreenW, 180+6+30)];
    self.screenshotsView.backgroundColor = [UIColor whiteColor];
    [self.footView addSubview:self.screenshotsView];
    
    UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 6)];
    view2.backgroundColor = RGB(245, 245, 245);
    [self.screenshotsView  addSubview:view2];
    
    UILabel   *label1  = [[UILabel alloc]initWithFrame:CGRectMake(15, 6, 100, 40)];
    label1.text = @"游戏截图";
    label1.text = [HWjianzhiduiObject keylocalization:@"游戏截图"];
    
    label1.font = [UIFont systemFontOfSize:14];
    label1.textColor = RGB(50, 50, 50);
    [self.screenshotsView addSubview:label1];
    
    UILabel   *label2  = [[UILabel alloc]initWithFrame:CGRectMake(kScreenW-200-15, 6, 200, 40)];
    label2.text = @"(最多可添加六张)";
    label2.font = [UIFont systemFontOfSize:12];
    label2.textColor = RGB(153, 153, 153);
    label2.textAlignment  =  NSTextAlignmentRight;
    [self.screenshotsView addSubview:label2];
    
    UIView *fengexianView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 45, kScreenW, 1)];
    fengexianView1.backgroundColor = RGB(232, 232, 242);
    [self.screenshotsView addSubview:fengexianView1];
    [self createCollectionView];
    
    
    
    
}



- (void)createCollectionView {
    UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc]init];
    self.collectionView =  [[UICollectionView alloc]initWithFrame:CGRectMake(15, 15+46, kScreenW -30, 80*2+30) collectionViewLayout:fl];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [self.screenshotsView addSubview:self.collectionView];
   // CGFloat spe =  (QCScreenW-62*4 - 30)/3;
    fl.minimumInteritemSpacing = 15;
    fl.minimumLineSpacing = 15;
    _collectionView.backgroundColor = [UIColor whiteColor];
    
   // [_collectionView registerClass:[PositioningCollectionView class] forCellWithReuseIdentifier:@"JXCell"];
    
    [_collectionView registerNib:[UINib nibWithNibName:@"ChooseCollectionViewCell" bundle:nil] forCellWithReuseIdentifier: @"JXCell"];
   // PositioningCollectionView
}


- (void)ChooseCollectionViewDelegate:(ChooseCollectionViewCell *)cell {
    NSIndexPath *inde = [self.collectionView indexPathForCell:cell];
    [self.dataMuArry removeObjectAtIndex:inde.row];
    max = max + 1;
    [self.collectionView reloadData];
    
    
    
    
    
}










//添加弹款视图
- (void)addBouncedView {
    
    self.maiHaoView = [[HWMainHaoView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
    self.maiHaoView.delegate = self;
    [kKeyWindow addSubview:self.maiHaoView];
    
    
    
    
    
}




// 放弃购买
- (void)HWSellTopViewGiveUpToBuy {
    
    [self.maiHaoView  removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
    

}

// 立即购买
- (void)HWSellTopViewBuy {
    
    [self.maiHaoView  removeFromSuperview];
    
    
}


// 添加低部UIview
- (void)addLowerPartView {
    
    self.lowerPartView = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenH-44-CF_TabbarSafeBottomMargin, kScreenW, 44+CF_TabbarSafeBottomMargin)];
    // self.lowerPartView.backgroundColor = [UIColor yellowColor];
    self.lowerPartView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.lowerPartView];
    UIView *fengexianView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 1)];
    fengexianView.backgroundColor = RGB(215, 215, 215);
    [self.lowerPartView addSubview:fengexianView];
    
    UIButton *butt  = [UIButton setButtonWithFrame:CGRectMake(65, 7, kScreenW-65*2, 30) Title:@"确认出售" Image:nil Font:13 Color:RGB(255, 255, 255) Target:self Selector:@selector(buttonChuShouTap:)];
    butt.backgroundColor = RGB(38, 154, 255);
    butt.layer.cornerRadius = 15;
    butt.layer.masksToBounds = YES;
    [self.lowerPartView addSubview:butt];
    

    
}

#pragma mark -----  点击立即下载按钮
- (void)buttonChuShouTap:(UIButton *)sender {
    
     DLog(@"确认出售");
    
    
    [self shujushanchuantupian];
    
    
    return;
    
    
    
    
  //   NSString *str1 = @
    NSIndexPath *inde0 =  [NSIndexPath indexPathForRow:0 inSection:0];
    HWMaiHaoCell *cell0 =  [self.mainaTableVie cellForRowAtIndexPath:inde0];
    
    NSIndexPath *inde1 = [NSIndexPath indexPathForRow:1 inSection:0];
    HWMaiHaoCell *cell1 =  [self.mainaTableVie cellForRowAtIndexPath:inde1];
    
    
    
    NSIndexPath *inde2 = [NSIndexPath indexPathForRow:2 inSection:0];
    HWMaiHaoCell *cell2 =  [self.mainaTableVie cellForRowAtIndexPath:inde2];
    
    

    NSIndexPath *inde3 = [NSIndexPath indexPathForRow:3 inSection:0];
       HWMaiHaoCell *cell3 =  [self.mainaTableVie cellForRowAtIndexPath:inde3];

    NSIndexPath *inde4 = [NSIndexPath indexPathForRow:4 inSection:0];
       HWMaiHaoCell *cell4 =  [self.mainaTableVie cellForRowAtIndexPath:inde4];
    
    NSIndexPath *inde5 = [NSIndexPath indexPathForRow:5 inSection:0];
    HWMaiHaoCell *cell5 =  [self.mainaTableVie cellForRowAtIndexPath:inde5];
    
    
    NSLog(@"%@ --- %@ ------ %@",cell0.nameTextField.text ,cell1.nameTextField.text,cell2.nameTextField.text);
    
    if (!(cell1.nameTextField.text.length > 0)) {
        
        [MBProgressHUD showError:@"操作系统不能为空"];
        return;
        
    } else if(!(cell3.nameTextField.text.length > 0)) {
        
         [MBProgressHUD showError:@"游戏区服不能为空"];
          return;
        
        
        
    } else if (!(cell4.nameTextField.text.length > 0)) {
        
        [MBProgressHUD showError:@"售价不能为空"];
         return;
            
        
    }
    NSString *xitong = cell1.nameTextField.text;
    if ([xitong isEqualToString:@"ios"]) {
        xitong = @"2";
    } else {
        
          xitong = @"1";
    }
    
    if (!(self.dataMuArry.count > 1)) {
        
        [MBProgressHUD showError:@"图片不能为空"];
        return;
    }
    
    
    if (!(_textView.text.length > 0)) {
        
        [MBProgressHUD showError:@"简介不能为空"];
        return;
    }
    
    
    if (!(cell2.nameTextField.text.length > 0)) {
        cell2.nameTextField.text = @"";
        
    }
    
    
    if (!(self.erjiTextField1.text.length > 0)) {
        
        self.erjiTextField1.text = @"";
        
        
        // [MBProgressHUD showError:@"二级密码不能为空"];
       //  return;
        
        
        
    }
    
    
    
    if (!(self.biaotinamete1feild.text.length > 0)) {
        [MBProgressHUD showError:@"标题不能为空"];
        return;
    }
    
    
    
    
    
    NSString *userID = [HWLocallyStoredData getLoginUserID];
    int t = [WMUtil getRandomNumber:101 to:998];
    NSString *tStr = [NSString stringWithFormat:@"%ld%d",[WMUtil getTimeSp],t];
    NSString *sign = [NSString stringWithFormat:@"%@%@%@",userID,tStr,@"fsd213ewdsadqwe2121213edsad"];
    NSString *signMD5 = [WMUtil md5HexDigest:sign];
    
    
     HWYouXixiaoHaoModel *modle =  self.chuanmodel.data[0];
    
    
    
  //  NSString *Bete64 = [self encodeToBase64String:self.cunchuImage];
                     //   };
   
   //  self.dataMuArry
    
    
    NSMutableArray * arr = [[NSMutableArray alloc]init];
    
    for (int i = 0; i < (self.dataMuArry.count-1); i++) {
        
        CasesIconItem *ite = self.dataMuArry[i];
        
        NSString *Bete64 = [self encodeToBase64String:ite.iconImage];
        
        [arr  addObject:Bete64];
        
        
    }
    
    
    
    NSString *ico =    [self  gs_jsonStringCompactFormatForNSArray:arr];
    
    NSDictionary *parametes = @{
                                @"ct" : @"app",
                                @"ac" : @"trade_add",
                                @"ios" : @"1",
                                @"uid" :userID,
                                @"t" :tStr,
                                @"sign":signMD5,
                                @"name": self.biaotinamete1feild.text,
                                @"introduction": _textView.text,
                                @"content":_textView.text,
                                @"gname" : cell0.nameTextField.text,
                                @"sname" :cell3.nameTextField.text,
                                @"gid" : modle.gid,
                                @"two_passwd" : @"123",
                                @"xuid": self.chuanmodel.uid,
                                @"money" :cell4.nameTextField.text,
                                @"system" : xitong,
                                @"images" :ico,
                                };
     //  @"images" :ico,
    
    [MBProgressHUD showMessage:@"正在提交...."];
    [HWWebUtils doPostWithParameters:parametes progress:nil success:^(id response) {
        
        NSString *codeStr =  [NSString stringWithFormat:@"%@",response[@"code"]];
          //   [MBProgressHUD hideHUD];
             
             
             if ([codeStr intValue] == 1) {
              
                 [self.navigationController popViewControllerAnimated:YES];
                 [MBProgressHUD  showError:@"提交成功"];
    

             } else {
                 
                  [MBProgressHUD  showError:response[@"message"]];
                 
             }
             NSLog(@"%@",response);
        
    } failure:^(NSString *error) {
         [MBProgressHUD  showError:@"加载失败"];
 
    }];
    
    
    
    
    
//    [HWWebUtils doGetWithParameters:parametes progress:nil success:^(id response) {
//
//
//        NSString *codeStr =  [NSString stringWithFormat:@"%@",response[@"code"]];
//     //   [MBProgressHUD hideHUD];
//
//
//        if ([codeStr intValue] == 1) {
//
//            [self.navigationController popViewControllerAnimated:YES];
//
//
//
//
//
//        } else {
//
//             [MBProgressHUD  showError:@"加载失败"];
//
//        }
//        NSLog(@"%@",response);
//
//
//    } failure:^(NSString *error) {
//
//        [MBProgressHUD  showError:@"加载失败"];
//
//    }];
    
    
    
    
    
    
    
       
  
     
}

// 数据上传图片

- (void)shujushanchuantupian {
    
    
    
    self.cunchuUrlStrMutabelArr = [[NSMutableArray alloc]init];
    
    
    
    if (self.dataMuArry.count == 0) {
        return;
    }
    
    if (!(self.dataMuArry.count > 1)) {
        
        [MBProgressHUD showError:@"图片不能为空"];
        return;
    }
    
     [MBProgressHUD showMessage:@"正在提交...."];
    
    for (int i = 0; i < (self.dataMuArry.count-1); i++) {
           
           CasesIconItem *ite = self.dataMuArry[i];
        
           AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                   //接收类型不一致请替换一致text/html或别的
                   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                                        @"text/html",
                                                                        @"image/jpeg",
                                                                        @"image/png",
                                                                        @"application/octet-stream",
                                                                        @"text/json",
                                                                        nil];

                  NSString *userID = [HWLocallyStoredData getLoginUserID];
        
                  int t =   [WMUtil  getRandomNumber:101 to:998];
              NSString *tStr = [NSString stringWithFormat:@"%ld%d",[WMUtil getTimeSp],t];
              NSString *sign = [NSString stringWithFormat:@"%@%@%@",userID,tStr,@"fsd213ewdsadqwe2121213edsad"];


              NSString *signMD5 = [WMUtil md5HexDigest:sign];




              NSDictionary *dic = @{@"uid":[HWLocallyStoredData getLoginUserID],@"t":tStr,@"sign":signMD5,@"image":@"image"};


                   //AppDelegate *myDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
                  // NSDictionary *dic = @{@"id":myDelegate.userId};
                  manager.responseSerializer = [AFHTTPResponseSerializer serializer];

                  NSString *url = [NSString stringWithFormat:@"%@?ct=app&ac=upload",[HWOCGlobalConst baseUrl]];

                   NSURLSessionDataTask *task = [manager POST:url parameters:dic  headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                       
                       NSData *imageDatas = UIImageJPEGRepresentation(ite.iconImage,1.0f);;
                       NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                       formatter.dateFormat = @"yyyyMMddHHmmss";
                       NSString *str = [formatter stringFromDate:[NSDate date]];
                       NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
                       //上传的参数(上传图片，以文件流的格式)
                       [formData appendPartWithFileData:imageDatas
                                                   name:@"image"
                                               fileName:fileName
                                               mimeType:@"image/jpeg"];
                   } progress:^(NSProgress * _Nonnull uploadProgress) {
                       //打印下上传进度
                       NSLog(@"上传进度");
                       NSLog(@"%@",uploadProgress);
                   } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                       //上传成功
                       NSLog(@"上传成功");
                       NSLog(@"%@",responseObject);
                      NSString * str  =[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                       
                       [self.cunchuUrlStrMutabelArr addObject:str];
                       
                       if (self.cunchuUrlStrMutabelArr.count == (self.dataMuArry.count-1) ) {
                           NSLog(@"vfijvijf");
                           [MBProgressHUD  hideHUD];
                           [self zuizhongshanchunchenggonghou];
                           
                         //   [MBProgressHUD  hideHUD];
                           
                       } else {
                           
                            [MBProgressHUD  hideHUD];
                           
                       }
                       
                       NSLog(@"上传成功");
                       NSLog(@"上传成功");
                      //  [self chuanURldaohoutai:str];


                   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                       //上传失败
                       NSLog(@"上传失败");
                       
                       [MBProgressHUD  hideHUD];
                   }];
        
          
        
        
           
    }
 
      
    
    
    
    
   

    
    
    
    
}


//最终请求数据
- (void)zuizhongshanchunchenggonghou {
    
    //   NSString *str1 = @
       NSIndexPath *inde0 =  [NSIndexPath indexPathForRow:0 inSection:0];
       HWMaiHaoCell *cell0 =  [self.mainaTableVie cellForRowAtIndexPath:inde0];
       
       NSIndexPath *inde1 = [NSIndexPath indexPathForRow:1 inSection:0];
       HWMaiHaoCell *cell1 =  [self.mainaTableVie cellForRowAtIndexPath:inde1];
       
       
       
       NSIndexPath *inde2 = [NSIndexPath indexPathForRow:2 inSection:0];
       HWMaiHaoCell *cell2 =  [self.mainaTableVie cellForRowAtIndexPath:inde2];
       
       

       NSIndexPath *inde3 = [NSIndexPath indexPathForRow:3 inSection:0];
          HWMaiHaoCell *cell3 =  [self.mainaTableVie cellForRowAtIndexPath:inde3];

       NSIndexPath *inde4 = [NSIndexPath indexPathForRow:4 inSection:0];
          HWMaiHaoCell *cell4 =  [self.mainaTableVie cellForRowAtIndexPath:inde4];
       
       NSIndexPath *inde5 = [NSIndexPath indexPathForRow:5 inSection:0];
       HWMaiHaoCell *cell5 =  [self.mainaTableVie cellForRowAtIndexPath:inde5];
       
       
       NSLog(@"%@ --- %@ ------ %@",cell0.nameTextField.text ,cell1.nameTextField.text,cell2.nameTextField.text);
       
       if (!(cell1.nameTextField.text.length > 0)) {
           
           [MBProgressHUD showError:@"操作系统不能为空"];
           return;
           
       } else if(!(cell3.nameTextField.text.length > 0)) {
           
            [MBProgressHUD showError:@"游戏区服不能为空"];
             return;
           
           
           
       } else if (!(cell4.nameTextField.text.length > 0)) {
           
           [MBProgressHUD showError:@"售价不能为空"];
            return;
               
           
       }
       NSString *xitong = cell1.nameTextField.text;
       if ([xitong isEqualToString:@"ios"]) {
           xitong = @"2";
       } else {
           
             xitong = @"1";
       }
       
       if (!(self.dataMuArry.count > 1)) {
           
           [MBProgressHUD showError:@"图片不能为空"];
           return;
       }
       
       
       if (!(_textView.text.length > 0)) {
           
           [MBProgressHUD showError:@"简介不能为空"];
           return;
       }
       
       
       if (!(cell2.nameTextField.text.length > 0)) {
           cell2.nameTextField.text = @"";
           
       }
       
       
       if (!(self.erjiTextField1.text.length > 0)) {
           
           self.erjiTextField1.text = @"";
           
           
           // [MBProgressHUD showError:@"二级密码不能为空"];
          //  return;
           
           
           
       }
       
       
       
       if (!(self.biaotinamete1feild.text.length > 0)) {
           [MBProgressHUD showError:@"标题不能为空"];
           return;
       }
       
       
       
       
       
       NSString *userID = [HWLocallyStoredData getLoginUserID];
       int t = [WMUtil getRandomNumber:101 to:998];
       NSString *tStr = [NSString stringWithFormat:@"%ld%d",[WMUtil getTimeSp],t];
       NSString *sign = [NSString stringWithFormat:@"%@%@%@",userID,tStr,@"fsd213ewdsadqwe2121213edsad"];
       NSString *signMD5 = [WMUtil md5HexDigest:sign];
       
       
        HWYouXixiaoHaoModel *modle =  self.chuanmodel.data[0];
       
       
       
     //  NSString *Bete64 = [self encodeToBase64String:self.cunchuImage];
                        //   };
      
      //  self.dataMuArry
       
       
       NSMutableArray * arr = [[NSMutableArray alloc]init];
       
//       for (int i = 0; i < (self.dataMuArry.count-1); i++) {
//
//           CasesIconItem *ite = self.dataMuArry[i];
//
//           NSString *Bete64 = [self encodeToBase64String:ite.iconImage];
//
//           [arr  addObject:Bete64];
//
//
//       }
//
//
    
     for (int i = 0 ; i < self.cunchuUrlStrMutabelArr.count; i++) {
         
           [arr addObject:self.cunchuUrlStrMutabelArr[i]];
         
        
      }
       
       
       
       NSString *ico =    [self  gs_jsonStringCompactFormatForNSArray:arr];
       
       NSDictionary *parametes = @{
                                   @"ct" : @"app",
                                   @"ac" : @"trade_add",
                                   @"ios" : @"1",
                                   @"uid" :userID,
                                   @"t" :tStr,
                                   @"sign":signMD5,
                                   @"name": self.biaotinamete1feild.text,
                                   @"introduction": _textView.text,
                                   @"content":_textView.text,
                                   @"gname" : cell0.nameTextField.text,
                                   @"sname" :cell3.nameTextField.text,
                                   @"gid" : modle.gid,
                                   @"two_passwd" : @"123",
                                   @"xuid": self.chuanmodel.uid,
                                   @"money" :cell4.nameTextField.text,
                                   @"system" : xitong,
                                   @"images" :ico,
                                   };
        //  @"images" :ico,
       
       [MBProgressHUD showMessage:@"正在提交...."];
       [HWWebUtils doPostWithParameters:parametes progress:nil success:^(id response) {
           
           NSString *codeStr =  [NSString stringWithFormat:@"%@",response[@"code"]];
             //   [MBProgressHUD hideHUD];
                
                
                if ([codeStr intValue] == 1) {
                 
                    [self.navigationController popViewControllerAnimated:YES];
                    [MBProgressHUD  showError:@"提交成功"];
       

                } else {
                    
                     [MBProgressHUD  showError:response[@"message"]];
                    
                }
                NSLog(@"%@",response);
           
       } failure:^(NSString *error) {
            [MBProgressHUD  showError:@"加载失败"];
    
       }];
    
    
    
    
    
    
    
    
    
    
}

















- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return  self.dataMuArr.count;
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellID = @"cellID";
    HWMaiHaoCell  *cell =  [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell =   [[HWMaiHaoCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    
    cell.backgroundColor = [UIColor whiteColor];
    HWSellNOModel  *mode =   self.dataMuArr[indexPath.row];
    cell.miaoShuLabel.text = mode.mingchenStr;
    cell.nameTextField.placeholder = mode.mishuString;
    cell.nameTextField.text = mode.neirongStr;
    
    if (mode.isdianji) {
          cell.nameTextField.userInteractionEnabled = YES;
    } else {
        cell.nameTextField.userInteractionEnabled = NO;
          
    }
    cell.nameTextField.delegate = self;
    
 //   cell.nameTextField.userInteractionEnabled = NO;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return  cell;
    

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
      NSLog(@"打印 %ld", indexPath.row);
      if (indexPath.row == 1) {
          
             UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择操作系统" message:nil preferredStyle:UIAlertControllerStyleAlert];
             UIAlertAction *videoAction = [UIAlertAction actionWithTitle:@"ios" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                 //
                 HWSellNOModel *model2 =  self.dataMuArr[1];
                   model2.neirongStr =  @"ios";
                  [self.mainaTableVie reloadData];
             }];
             [videoAction setValue:wholeProjectBlackFontColor forKey:@"_titleTextColor"];
             UIAlertAction *gifAction = [UIAlertAction actionWithTitle:@"Android" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                // [self photoAlbumImage];
                 HWSellNOModel *model2 =  self.dataMuArr[1];
                 model2.neirongStr =  @"Android";
                 [self.mainaTableVie reloadData];
            
             }];
             
             // KVC 改变颜色
             [gifAction setValue:wholeProjectBlackFontColor forKey:@"_titleTextColor"];
             
//             UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//
//             }];
//             // KVC 改变颜色
//             [cancelAction setValue:wholeProjectBlackFontColor forKey:@"_titleTextColor"];
             
             [alert addAction:videoAction];
             [alert addAction:gifAction];
         //    [alert addAction:cancelAction];
             [self presentViewController:alert animated:YES completion:nil];
             
        
      }
    
    
    
    
    
    
    
    
    
}







- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}


//第一个方法用于限制输入，第二个方法用于动态计算剩余字数
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range

 replacementText:(NSString *)text

{
    
    


    UITextRange *selectedRange = [textView markedTextRange];

    //获取高亮部分

    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];

    //获取高亮部分内容

    //NSString * selectedtext = [textView textInRange:selectedRange];

    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
             //在这里做你响应return键的代码
           
        [textView resignFirstResponder];
           
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
      
      

    //如果有高亮且当前字数开始位置小于最大限制时允许输入

    if (selectedRange && pos) {

        NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];

        NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];

        NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);

        

        if (offsetRange.location < MAX_LIMIT_NUMS) {

            return YES;
            
            

        }

        else

        {
            [MBProgressHUD showError:@"最多只能输入120个字符"];

            return NO;

        }

    }

   

    

    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];

    

    NSInteger caninputlen = MAX_LIMIT_NUMS - comcatstr.length;

    

    if (caninputlen >= 0)

    {

        return YES;

    }

    else

    {

        NSInteger len = text.length + caninputlen;

        //防止当text.length + caninputlen < 0时，使得rg.length为一个非法最大正数出错

        NSRange rg = {0,MAX(len,0)};

        

        if (rg.length > 0)

        {

            NSString *s = @"";

            //判断是否只普通的字符或asc码(对于中文和表情返回NO)

            BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];

            if (asc) {

                s = [text substringWithRange:rg];//因为是ascii码直接取就可以了不会错

            }

            else

            {

                __block NSInteger idx = 0;

                __block NSString  *trimString = @"";//截取出的字串

                //使用字符串遍历，这个方法能准确知道每个emoji是占一个unicode还是两个

                [text enumerateSubstringsInRange:NSMakeRange(0, [text length])

                                         options:NSStringEnumerationByComposedCharacterSequences

                                      usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {

                                          

                                          if (idx >= rg.length) {

                                              *stop = YES; //取出所需要就break，提高效率

                                              return ;

                                          }

                                          

                                          trimString = [trimString stringByAppendingString:substring];

                                          

                                          idx++;

                                      }];

                

                s = trimString;

            }

            //rang是指从当前光标处进行替换处理(注意如果执行此句后面返回的是YES会触发didchange事件)

            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];

            //既然是超出部分截取了，哪一定是最大限制了。

         //   self.remainLabel.text = [NSString stringWithFormat:@"您最多还可以输入%d个字",0];

        }
        
        
         [MBProgressHUD showError:@"最多只能输入120个字符"];

        return NO;

    }

    

}




 

- (void)textViewDidChange:(UITextView *)textView

{

    UITextRange *selectedRange = [textView markedTextRange];

    //获取高亮部分

    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];

    

    //如果在变化中是高亮部分在变，就不要计算字符了

    if (selectedRange && pos) {

        return;

    }

    

    NSString  *nsTextContent = textView.text;

    NSInteger existTextNum = nsTextContent.length;

    

    if (existTextNum > MAX_LIMIT_NUMS)

    {

        //截取到最大位置的字符(由于超出截部分在should时被处理了所在这里这了提高效率不再判断)

        NSString *s = [nsTextContent substringToIndex:MAX_LIMIT_NUMS];

        

        [textView setText:s];

    }

    

    //不让显示负数

 //   self.remainLabel.text = [NSString stringWithFormat:@"您最多还可以输入%ld个字",MAX(0,MAX_LIMIT_NUMS - existTextNum)];

}



- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
       [textField resignFirstResponder];
    
    return YES;
    
}



//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataMuArry.count;
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier =@"JXCell";
 //   ChooseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    ChooseCollectionViewCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    
    cell.choosedelegate = self;
    cell.model = self.dataMuArry[indexPath.row];
    return cell;
    
    
    
    
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(80, 80);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    //  UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)
    return UIEdgeInsetsMake(0, 0, 0, 0);
}





- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
     CasesIconItem  *model  = self.dataMuArry[indexPath.row];
    if (model.isdelete == NO) {
        [self setUPUserImage];
    } else {
        
    }
    
    
}




#pragma  mark  ------------  点击更换头像
- (void)setUPUserImage {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *videoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        //
        if (max < 1) {
            [MBProgressHUD showError:@"图片上床只能大于六张"];
            return;
        }
        [self picturesImage];
    }];
    [videoAction setValue:wholeProjectBlackFontColor forKey:@"_titleTextColor"];
    UIAlertAction *gifAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
       // [self photoAlbumImage];
        if (max < 1) {
            [MBProgressHUD showError:@"图片上床只能大于六张"];
            return;
        }
        [self selectPhoto];
    }];
    
    // KVC 改变颜色
    [gifAction setValue:wholeProjectBlackFontColor forKey:@"_titleTextColor"];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    // KVC 改变颜色
    [cancelAction setValue:wholeProjectBlackFontColor forKey:@"_titleTextColor"];
    
    [alert addAction:videoAction];
    [alert addAction:gifAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
    
    
}

//点击拍照
- (void)picturesImage {
    
    
    
    
    BOOL result = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    
    if (result) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePicker animated:YES completion:nil];
        
        
    }else{
        //        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请在设置-->隐私-->相机，中开启本应用的相机访问权限！！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"我知道了", nil];
        //        [alert show];
        
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在设置-->隐私-->相机，中开启本应用的相机访问权限！！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *videoAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
        }];
        [videoAction setValue:wholeProjectBlackFontColor forKey:@"_titleTextColor"];
        UIAlertAction *gifAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
        }];
        // KVC 改变颜色
        [gifAction setValue:wholeProjectBlackFontColor forKey:@"_titleTextColor"];
        [alert addAction:videoAction];
        [alert addAction:gifAction];
        [self presentViewController:alert animated:YES completion:nil];
        //
        
        
    }
    
    
}


////点击相册
//- (void)photoAlbumImage {
//
//    BOOL result = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
//    if (result) {
//        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
//        imagePicker.delegate = self;
//        imagePicker.allowsEditing = YES;
//        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//        //                        [self presentModalViewController:imagePicker animated:YES];
//        [self presentViewController:imagePicker animated:YES completion:nil];
//    }else{
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请在设置-->隐私-->相机，中开启本应用的相机访问权限！！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"我知道了", nil];
//        [alert show];
//    }
//
//
//}


#pragma  mark ---------  UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info {
    UIImage *userImage = [self fixOrientation:(UIImage *)info[UIImagePickerControllerEditedImage]];
    // UIImagePickerControllerOriginalImage

    
    // 图片缩放
    userImage = [self scaleImage:userImage toScale:0.3];
    
    max = max - 1;
   
    CasesIconItem  *p1 = [[CasesIconItem alloc]init];
    p1.iconImage = userImage;
    p1.isdelete = YES;
    //self.dataMuArry.count - 1
    [self.dataMuArry insertObject:p1 atIndex:self.dataMuArry.count - 1];
    [self.collectionView reloadData];
    

    //    照片上传
    // [self upDateHeadIcon:userImage];
    //保存图片 保存到沙河
    //   [self saveImage:userImage name:@"touxiang"];
    
    // QrCodeableViewCell *qrCodCell = [tableView dequeueReusableCellWithIdentifier:qrCodID];

    //往配图相册view里面添加图片
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
//    //    修正照片方向(手机转90度方向拍照)
//    UIImage *userImage = [self fixOrientation:[editingInfo objectForKey:@"UIImagePickerControllerOriginalImage"]];
//
//    // 图片缩放
//    userImage = [self scaleImage:userImage toScale:0.3];
//
//    //    照片上传
//   // [self upDateHeadIcon:userImage];
//    //保存图片 保存到沙河
//  //   [self saveImage:userImage name:@"touxiang"];
//
//    //往配图相册view里面添加图片
//    [picker dismissViewControllerAnimated:YES completion:nil];
//}


//修正照片方向(手机转90度方向拍照)
- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

//缩放图片
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSLog(@"%@",NSStringFromCGSize(scaledImage.size));
    return scaledImage;
}

//保存照片到沙盒路径(保存)
- (void)saveImage:(UIImage *)image name:(NSString *)iconName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    //写入文件
    NSString *icomImage = iconName;
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", icomImage]];
    // 保存文件的名称
    //    [[self getDataByImage:image] writeToFile:filePath atomically:YES];
    [UIImagePNGRepresentation(image) writeToFile: filePath  atomically:YES];
}

//上传图片
- (void)upDateHeadIcon:(UIImage *)photo
{
    if (photo == nil) {
        return;
    }
    
    
}




- (void )selectPhoto {
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
        if (status != PHAuthorizationStatusAuthorized) return;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // 弹出图片选择界面
            CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
            // 隐藏空相册
            picker.showsEmptyAlbums = NO;
            // 显示图片索引
            picker.showsSelectionIndex = YES;
            
            picker.assetCollectionSubtypes = @[
                                               @(PHAssetCollectionSubtypeSmartAlbumUserLibrary),
                                               @(PHAssetCollectionSubtypeAlbumRegular)
                                               ];
            picker.delegate = self;
            
            if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { // 如果当前运行的设备是平板电脑
                picker.modalPresentationStyle = UIModalPresentationFormSheet;
            }
            
            [self presentViewController:picker animated:YES completion:nil];
        });
    }];
}

#pragma mark - <CTAssetsPickerControllerDelegate>
- (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
{
   // NSInteger max = 9;
    
    if (picker.selectedAssets.count < max) return YES;
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"注意"
                                                                   message:[NSString stringWithFormat:@"最多选择%zd张图片", max]
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil]];
    // 这里一定要用picker，不能使用self（因为当前显示在上面的控制器是picker，不是self）
    [picker presentViewController:alert animated:YES completion:nil];
    
    return NO;
}

/**
 *  选择完毕的时候调用
 */
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    // 关闭图片选择界面
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    // 选择图片时的配置项
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.resizeMode   = PHImageRequestOptionsResizeModeExact;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    
    // 显示图片
    for (NSInteger i = 0; i < assets.count; i++) {
        PHAsset *asset = assets[i];
        CGSize size = CGSizeMake(asset.pixelWidth / [UIScreen mainScreen].scale, asset.pixelHeight / [UIScreen mainScreen].scale);
        
        // 请求图片
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            // 添加图片控件
//            UIImageView *imageView = [[UIImageView alloc] init];
//            imageView.image = result;
//            [self.view addSubview:imageView];
//
//            imageView.frame = CGRectMake((i % 3) * (100 + 10), (i / 3) * (100 + 10), 100, 100);
            CasesIconItem  *p1 = [[CasesIconItem alloc]init];
            
            
            
            p1.iconImage = result;
            p1.isdelete = YES;
            //self.dataMuArry.count - 1
            max = max - 1;
            [self.dataMuArry insertObject:p1 atIndex:self.dataMuArry.count - 1];
            [self.collectionView reloadData];
            
            
        }];
    }
}



- (NSString*)encodeToBase64String:(UIImage*)image {

    return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    

}


-(NSString *)convertToJsonData:(NSDictionary *)dict {
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}


- (NSString *)gs_jsonStringCompactFormatForNSArray:(NSArray *)arrJson {

    

    if (![arrJson isKindOfClass:[NSArray class]] || ![NSJSONSerialization isValidJSONObject:arrJson]) {

        return nil;

    }

    

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arrJson options:0 error:nil];

    NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    return strJson;

}




@end
